//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { useSeaOtterStores } from "../store";
import { observer } from 'mobx-react';
import { Button, Card, Checkbox, Descriptions, Form, message, Modal, Popover, Space, Table } from "antd";
import { get as get_group, remove as remove_group } from "@/api/seaotter/image_group";
import type { ImageInfo } from "@/api/seaotter/image";
import { list_image, remove_image } from "@/api/seaotter/image";
import { get_session, get_user_id } from "@/api/user";
import { request } from "@/utils/request";
import { gen_access_token } from "@/api/project_server";
import { MoreOutlined } from "@ant-design/icons";
import EditGroupModal from "./EditGroupModal";
import UserPhoto from "@/components/Portrait/UserPhoto";
import moment from "moment";
import type { ColumnsType } from 'antd/lib/table';

const PAGE_SIZE = 20;

const ImageInfoList = () => {
    const appStore = useSeaOtterStores();

    const [canRemoveGroup, setCanRemoveGroup] = useState(false);
    const [canRemoveImage, setCanRemoveImage] = useState(false);

    const [imageInfoList, setImageInfoList] = useState<ImageInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [showUpdateGroupModal, setShowUpdateGroupModal] = useState(false);
    const [showRemoveGroupModal, setShowRemoveGroupModal] = useState(false);

    const [removeImageInfo, setRemoveImageInfo] = useState<ImageInfo | null>(null);
    const [forceRemoveImage, setForceRemoveImage] = useState(false);

    const calcRemovePerm = async () => {
        if (appStore.curImageGroup == null) {
            setCanRemoveGroup(false);
            setCanRemoveImage(false);
            return;
        }
        //只有管理员可以删除分组
        setCanRemoveGroup(appStore.adminUser && (appStore.curImageGroup.image_info_count == 0));

        const prjPermInfo = appStore.curImageGroup.perm_info.member_perm[appStore.projectId];
        if (prjPermInfo == undefined || prjPermInfo == null) {
            setCanRemoveImage(false);
            return;
        }
        const myUserId = await get_user_id();
        setCanRemoveImage(prjPermInfo.member_user_id_for_remove.includes(myUserId));
    };

    const loadGroupInfo = async () => {
        if (appStore.curImageGroup == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        const getRes = await request(get_group(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: appStore.curImageGroup.group_name,
        }));

        appStore.curImageGroup = getRes.group;
    }

    const loadImageInfoList = async () => {
        if (appStore.curImageGroup == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        const listRes = await request(list_image(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: appStore.curImageGroup.group_name,
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setTotalCount(listRes.total_count);
        setImageInfoList(listRes.image_list);
    };

    const removeGroup = async () => {
        if (appStore.curImageGroup == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        await request(remove_group(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: appStore.curImageGroup.group_name,
        }));
        message.info("删除成功");
        appStore.curImageGroup = null;
        appStore.incRroupDataVersion();
    };

    const removeImage = async () => {
        if (removeImageInfo == null) {
            return;
        }
        if (appStore.curImageGroup == null) {
            return;
        }
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        await request(remove_image(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            group_name: removeImageInfo.group_name,
            image_name: removeImageInfo.image_name,
            force: forceRemoveImage,
        }));
        message.info("删除镜像信息成功");
        await loadGroupInfo();
        await loadImageInfoList();

        setRemoveImageInfo(null);
        setForceRemoveImage(false);
    };

    const columns: ColumnsType<ImageInfo> = [
        {
            title: "镜像名称",
            render: (_, row: ImageInfo) => (
                <a onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    appStore.curImage = row.image_name;
                }}>{row.image_name}</a>
            )
        },
        {
            title: "版本数量",
            width: 80,
            dataIndex: "reference_count",
        },
        {
            title: "创建时间",
            width: 150,
            render: (_, row: ImageInfo) => moment(row.create_time).format("YYYY-MM-DD HH:mm:ss"),
        },
        {
            title: "更新时间",
            width: 150,
            render: (_, row: ImageInfo) => moment(row.update_time).format("YYYY-MM-DD HH:mm:ss"),
        },
        {
            title: "操作",
            width: 100,
            render: (_, row: ImageInfo) => (
                <>
                    {canRemoveImage == true && (
                        <Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }} danger
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveImageInfo(row);
                            }}>删除</Button>
                    )}
                </>
            ),
        }
    ];


    useEffect(() => {
        if (appStore.curImageGroup != null) {
            calcRemovePerm();
            if (curPage != 0) {
                setCurPage(0);
            } else {
                loadImageInfoList();
            }
        }
    }, [appStore.curImageGroup]);

    useEffect(() => {
        loadImageInfoList();
    }, [curPage]);

    return (
        <>
            {appStore.curImageGroup != null && (
                <Card title={<span style={{ fontSize: "20px", fontWeight: 700 }}>{appStore.curImageGroup.group_name}</span>}
                    bodyStyle={{ height: "calc(100vh - 100px)", overflowY: "scroll" }} bordered={false}
                    extra={
                        <>
                            {(canRemoveGroup || appStore.adminUser) && (
                                <Popover placement="bottom" trigger="click" content={
                                    <Space direction="vertical">
                                        {appStore.adminUser && (
                                            <Button type="link" onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setShowUpdateGroupModal(true);
                                            }}>调整权限</Button>
                                        )}
                                        {canRemoveGroup && (
                                            <Button type="link" danger onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setShowRemoveGroupModal(true);
                                            }}>删除</Button>
                                        )}
                                    </Space>
                                }>
                                    <MoreOutlined />
                                </Popover>
                            )}
                        </>
                    }>
                    <Descriptions column={2} bordered labelStyle={{ width: "100px" }} contentStyle={{ width: "calc(50vw - 220px)" }}>
                        <Descriptions.Item label="访问权限">
                            {appStore.curImageGroup.perm_info.public_group == true && "公开访问"}
                            {appStore.curImageGroup.perm_info.public_group == false && (
                                <Space style={{ flexWrap: "wrap" }}>
                                    {appStore.projectMemberList.filter(item => (appStore.curImageGroup!.perm_info.member_perm[appStore.projectId]?.member_user_id_for_view ?? []).includes(item.member_user_id)).map(prjMember => (
                                        <Space key={prjMember.member_user_id}>
                                            <UserPhoto logoUri={prjMember.logo_uri} style={{ width: "20px", height: "20px", borderRadius: "10px" }} />
                                            {prjMember.display_name}
                                        </Space>
                                    ))}
                                </Space>
                            )}
                        </Descriptions.Item>
                        <Descriptions.Item label="删除镜像">
                            <Space style={{ flexWrap: "wrap" }}>
                                {appStore.projectMemberList.filter(item => (appStore.curImageGroup!.perm_info.member_perm[appStore.projectId]?.member_user_id_for_remove ?? []).includes(item.member_user_id)).map(prjMember => (
                                    <Space key={prjMember.member_user_id}>
                                        <UserPhoto logoUri={prjMember.logo_uri} style={{ width: "20px", height: "20px", borderRadius: "10px" }} />
                                        {prjMember.display_name}
                                    </Space>
                                ))}
                            </Space>
                        </Descriptions.Item>
                        <Descriptions.Item label="拉取密钥">
                            <Space style={{ flexWrap: "wrap" }}>
                                {appStore.curImageGroup.perm_info.pull_secret_name_list.map(name => (
                                    <span key={name}>{name}</span>
                                ))}
                            </Space>
                        </Descriptions.Item>
                        <Descriptions.Item label="推送密钥">
                            <Space style={{ flexWrap: "wrap" }}>
                                {appStore.curImageGroup.perm_info.push_secret_name_list.map(name => (
                                    <span key={name}>{name}</span>
                                ))}
                            </Space>
                        </Descriptions.Item>
                        <Descriptions.Item label="创建时间">
                            {moment(appStore.curImageGroup.create_time).format("YYYY-MM-DD HH:mm:ss")}
                        </Descriptions.Item>
                        <Descriptions.Item label="更新时间">
                            {moment(appStore.curImageGroup.update_time).format("YYYY-MM-DD HH:mm:ss")}
                        </Descriptions.Item>
                    </Descriptions>
                    <Table rowKey="image_name" dataSource={imageInfoList} columns={columns}
                        pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), showSizeChanger: false, hideOnSinglePage: true }} />
                </Card>
            )}



            {showUpdateGroupModal == true && appStore.curImageGroup != null && (
                <EditGroupModal imageGroup={appStore.curImageGroup} onCancel={() => setShowUpdateGroupModal(false)}
                    onOk={() => {
                        setShowUpdateGroupModal(false);
                        loadGroupInfo();
                        appStore.incRroupDataVersion();
                    }} />
            )}
            {showRemoveGroupModal == true && (
                <Modal open title="删除当前镜像分组" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowRemoveGroupModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeGroup();
                    }}>
                    是否删除当前镜像分组?
                </Modal>
            )}
            {removeImageInfo != null && (
                <Modal open title="删除镜像信息" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveImageInfo(null);
                        setForceRemoveImage(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeImage();
                    }}>
                    <Form>
                        <Form.Item>
                            是否删除镜像信息&nbsp;{removeImageInfo.image_name}&nbsp;?
                        </Form.Item>
                        <Form.Item>
                            <Checkbox checked={forceRemoveImage} onChange={e => {
                                e.stopPropagation();
                                setForceRemoveImage(e.target.checked);
                            }}>强制删除</Checkbox>
                        </Form.Item>
                    </Form>
                </Modal>
            )}
        </>
    );
};



export default observer(ImageInfoList);